#define _CRT_SECURE_NO_WARNINGS 1

#include "game.h"

//八个方向排雷
int dx[8] = { -1,-1,-1,0,1,1,1,0 };
int dy[8] = { -1,0,1,1,1,0,-1,-1 };

void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
		{
			board[i][j] = set;
		}
	}
}

void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
	printf("---------扫雷---------\n");
	for (int i = 0; i <= col; i++) printf("%d ", i);
	printf("\n");
	for (int i = 1; i <= row; i++)
	{
		printf("%d ", i);
		for (int j = 1; j <= col; j++)
		{
			printf("%c ", board[i][j]);
		}
		printf("\n");
	}
}

void SetMine(char board[ROWS][COLS], int row, int col)
{
	int count = EASY_COUNT;
	while (count)
	{
		int x = 1 + rand() % row;
		int y = 1 + rand() % col;
		if (board[x][y] == '0') {
			board[x][y] = '1';
			count--;
		}
	}
}

int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
	int count = 0;
	for (int i = 0; i < 8; i++)
	{
		count += (mine[x + dx[i]][y + dy[i]] - '0');
	}
	return count;
}

void FindAroundMine(char mine[ROWS][COLS], char show[ROWS][COLS], int x, int y, int row, int col ,int* win)
{
	// 添加检查：仅处理未展开的格子（重要）
	if (show[x][y] != '*') {
		return;
	}
	int count = GetMineCount(mine, x, y);
	show[x][y] = (count + '0');
	(*win)++;
	if (!count) {
		for (int i = 0; i < 8; i++) {
			if ((x + dx[i]) >= 1 && (x + dx[i]) <= row && (y + dy[i]) >= 1 && (y + dy[i]) <= col) {
				FindAroundMine(mine, show, x + dx[i], y + dy[i], row, col, win);
			}
		}
	}
}

void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
	int x, y;
	int win = 0;
	while (win < (row * col - EASY_COUNT))
	{
		printf("请选择要排查雷的坐标：");
		scanf("%d %d", &x, &y);
		if (x<1 || x>row || y<1 || y>col) {
			printf("输入的坐标有误，x(%d-%d),y(%d-%d)\n", 1, row, 1, col);
		}
		else {
			if (mine[x][y] == '1') {
				printf("很遗憾，你踩雷了，游戏结束\n");
				printf("全部雷的位置如下：\n");
				DisplayBoard(mine, ROW, COL);
				break;
			}
			else {
				FindAroundMine(mine, show, x, y, row, col, &win);
				/*int count = GetMineCount(mine, x, y);
				show[x][y] = (count + '0');
				win++;*/
				DisplayBoard(show, ROW, COL);
			}
		}
	}
	if (win == (row * col - EASY_COUNT)) {
		printf("恭喜你，排雷成功\n");
		printf("全部雷的位置如下：\n");
		DisplayBoard(mine, ROW, COL);
	}
}